package com.xiake.utils;

import java.io.File;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

public class SendEmailThread implements Runnable {
	private static final Logger logger = LoggerFactory.getLogger("mail");
	private JavaMailSender mailSender;
	private String subject;
	private String to;
	private String text;
	private File file;
	private String from;
	
	public SendEmailThread(JavaMailSender mailSender, String subject, String from, String to, String text, File file) {
		this.mailSender = mailSender;
		this.subject = subject;
		this.to = to;
		this.text = text;
		this.file = file;
		this.from = from;
	}

	@Override
	public void run() {
		int i = 0;
		// 建立邮件消息,发送简单邮件和html邮件的区别
		while (true) {
			i++;
			if(i > 15){
				break;
			}
			MimeMessage mail = mailSender.createMimeMessage();
			// Address address = new Address
			/*
			 * try { mail.setFrom(); } catch (MessagingException e2) { // TODO
			 * Auto-generated catch block e2.printStackTrace(); }
			 */
			// 注意这里的boolean,等于真的时候才能嵌套图片，在构建MimeMessageHelper时候，所给定的值是true表示启用，
			// multipart模式 为true时发送附件 可以设置html格式
			// mail.set
			MimeMessageHelper messageHelper;
			try {
				messageHelper = new MimeMessageHelper(mail, true, "utf-8");
				messageHelper.setFrom(from);
				// messageHelper.set
				messageHelper.setTo(to);
				messageHelper.setSubject(subject);
				messageHelper.setText(text, true);
				if (file != null) {
					FileSystemResource img = new FileSystemResource(file);
					messageHelper.addAttachment(MimeUtility.encodeWord(file.getName()), img);
				}
				mailSender.send(mail);
				logger.info("发送邮件成功,收件人:"+to + ",发送邮箱:"+from + ",主题:"+subject);
				break;
			} catch (Exception e) {
				StringBuffer sb = new StringBuffer("");
				sb.append("发送邮件失败,收件人:"+to + ",发送邮箱:"+from + ",主题:"+subject+"错误信息:\n"+e.getMessage()+"\n");
				for (StackTraceElement str : e.getStackTrace()) {
					sb.append(str + "\n");
				}
				e.printStackTrace();
				logger.info(sb.toString());
				try {
					Thread.sleep(5 * 60 * 1000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
					break;
				}
			}
		}
		System.out.println("发送成功:" + to);

	}

}
